<template>
    <div v-loading="loading">
        <el-card>
            <template #header>
                <div>添加选项</div>
            </template>
            <!-- 插入表单 -->
            <el-form label-width="80px" :model="form" :rules="rules">
                <el-form-item label="选项名称" prop="itemname">
                    <el-input v-model="form.itemname"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addItemLogin">保存</el-button>
                    <el-button @click="$router.push({ name: 'ItemsIndex' })">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>

import { mapActions } from "vuex";
export default {
    data() {
        return {
            loading: false,
            form: {
                itemname: "",
            },
            rules: {
                itemname: [
                    {
                        required: true,
                        message: "选项名称不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 18,
                        min: 2,
                        message: "2-18个字符",
                    },
                    // 自定义验证规则
                    // {
                    //     validator: (rule, value, cb) => {
                    //         if (/^\w{2,18}$/.test(value)) {
                    //             cb();
                    //         } else {
                    //             cb(new Error("选项名称必须2-18个字符"));
                    //         }
                    //     }
                    // },
                    // 验证：当用户名存在时，验证不通过
                    {
                        validator: (rule, value, cb) => {
                            const { data } = this.exist({
                                field: "itemname",
                                value,
                            });
                            if (data) {
                                cb(new Error("选项名称已存在"));
                            } else {
                                cb();
                            }
                        },
                        // 失去焦点时，再做验证
                        trigger: "blur",
                    },
                ],
            },
        }
    },
    methods: {
        ...mapActions("items", ["addItem", "exist"]),
        async addItemLogin() {
            this.loading = true;
            const data = { itemname: this.form.itemname };
            // 判断选项是否有 id
            if (this.$route.query.id) {
                data.pid = this.$route.query.id;
            }
            try {
                await this.addItem(data);
                this.$message.success("选项添加成功！");
                this.$router.push({ name: 'ItemsIndex' });
            } catch (error) { }
            this.loading = false;
        },
    }
}
</script>